//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import type { LocalRepoFileChangeInfo } from "@/api/local_repo";
import { get_commit_change, get_file_diff } from "@/api/local_repo";
import { Card, Collapse, Select, message } from "antd";
import ReactDiffViewer from 'react-diff-viewer';
import { report_error } from "@/api/client_cfg";

interface DiffViewerProps {
    path: string;
    commitId: string;
    fileName: string;
    darkMode: boolean;
}

const DiffViewer = (props: DiffViewerProps) => {
    const [oldContent, setOldContent] = useState("");
    const [newContent, setNewContent] = useState("");

    const loadDiffInfo = async () => {
        const res = await get_file_diff(props.path, props.commitId, props.fileName);
        setNewContent(res.new_content.replaceAll("\r\n", "\n"));
        setOldContent(res.old_content.replaceAll("\r\n", "\n"));
    };

    useEffect(() => {
        loadDiffInfo();
    }, []);

    return (
        <>
            {(newContent !== "" || oldContent !== "") && (
                <ReactDiffViewer
                    oldValue={oldContent}
                    newValue={newContent}
                    splitView={false}
                    disableWordDiff={true}
                    useDarkTheme={props.darkMode}
                    showDiffOnly={true} />
            )}
        </>
    );
};

const DiffPanel = () => {
    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const path = urlParams.get("path") ?? "";
    const commitId = urlParams.get("commitId") ?? "";
    const summary = urlParams.get("summary") ?? "";
    const commiter = urlParams.get("commiter") ?? "";
    const fileName = urlParams.get("fileName") ?? "";

    const [changeList, setChangeList] = useState<LocalRepoFileChangeInfo[] | null>(null);
    const [darkMode, setDarMode] = useState(false);

    const loadChangeList = async () => {
        if (changeList !== null) {
            return;
        }
        try {
            const res = await get_commit_change(path, commitId);
            if (fileName == "") {
                setChangeList(res);
            } else {
                setChangeList(res.filter(item => item.new_file_name == fileName));
            }
        } catch (e) {
            console.log(e);
            report_error({
                err_data: `${e}`,
            });
            message.error(`${e}`);
        }
    };

    useEffect(() => {
        if (path !== "" && commitId !== "") {
            loadChangeList();
        }
    }, [path, commitId]);

    return (
        <Card title={`${commiter}: ${summary}`} bodyStyle={{ overflowY: "auto", height: "calc(100vh - 30px)" }} bordered={false}
            extra={
                <Select value={darkMode} style={{ width: 100 }} onChange={value => setDarMode(value)}>
                    <Select.Option value={false}>浅色模式</Select.Option>
                    <Select.Option value={true}>深色模式</Select.Option>
                </Select>
            }>
            {changeList !== null && (
                <Collapse accordion defaultActiveKey={changeList.length > 0 ? changeList[0].new_file_name : ""}>
                    {changeList.map(changeItem => (
                        <Collapse.Panel
                            header={changeItem.old_file_name == changeItem.new_file_name ? changeItem.new_file_name : `${changeItem.old_file_name} => ${changeItem.new_file_name}`}
                            key={changeItem.new_file_name}>
                            <DiffViewer path={path} commitId={commitId} fileName={changeItem.new_file_name} darkMode={darkMode} />
                        </Collapse.Panel>
                    ))}
                </Collapse>
            )}

        </Card>
    );
};

export default DiffPanel;